#encoding: utf-8
from pyecharts import options as opts
from pyecharts.charts import Pie

from utils.sqls import ExecuteSql

# **********************前后端代码分离********************
# 定义函数：设置饼图中心文案的样式
def new_label_opts(planName, runTime, succCount, failCount):
    msgCenter = '%s\n\n%s\n成功：%d\n失败：%d' %(planName, runTime, succCount, failCount)
    op = opts.LabelOpts(
        position="center",
        color='black',
        is_show=True,
        font_size=13,
        font_style='normal',
        font_weight='lighter',
        font_family='新宋体',
        formatter=msgCenter
    )
    return op

# 自定义生成饼图的函数，根据传参可以设置展示什么图形以及设置获取数据源方式，先期只支持饼图
def myCharts(datas, chartType='pie', dataFrom='inner'):
    if not isinstance(datas, (tuple, list)):
        return 'datas的数据类型必须为列表或者元组'

    if str(dataFrom).lower() == 'inner':
        datas = ExecuteSql(2)
    if chartType.lower() == 'pie':
        c = Pie()
        row_1_x_start = 10
        row_1_y_start = 20
        pieNum = min(15, len(datas))
        countPie = 0
        for i in range(0,3):
            for j in range(0, 5):
                row_1_x = str(row_1_x_start + 20*j) + "%"
                row_1_y = str(row_1_y_start + 30*i) + "%"
                if countPie < pieNum:
                    plan_name = plan_name_tem = str(datas[countPie][0])
                    run_time = str(datas[countPie][3])
                    succCount = datas[countPie][1]
                    failCount = datas[countPie][2]

                    if len(plan_name) < 18:
                        plan_name = plan_name[:9] + '\n' + plan_name[9:17]
                    else:
                        plan_name = plan_name[:9] + '\n' + plan_name[9:17] + '...'
                    c.add(
                        plan_name_tem,
                        data_pair=[list(z) for z in zip(['成功', '失败'], [succCount, failCount])],
                        center=[row_1_x, row_1_y],
                        radius=[75, 120],
                        label_opts=new_label_opts(plan_name, run_time, succCount, failCount),
                    )

                    countPie += 1
                else:
                    break
        c.set_colors(["#32CD32", "#FF0000"])
        c.set_global_opts(
            legend_opts=opts.LegendOpts(is_show=True, pos_right='5%'),
        )
        c.set_series_opts(
            tooltip_opts=opts.TooltipOpts(
                trigger="item", formatter="{a}<br/>{b}：{c}（{d}%）"
            ),
        )
        return c

# ********************************** 生成html文件 ******************************
# from pyecharts.commons.utils import JsCode
# import config
# renderHtmlPath = config.BASE_DIR + "/templates/chartsHtml/mutiple_pie.html"
#
# fn = """
#     function(params) {
#         if(params.name == '时间')
#             return '\\n\\n\\n\\n' + params.value;
#         if(params.name == '成功')
#             return '\\n\\n\\n\\n\\n\\n\\n' + params.name + ' : ' + params.value;
#         if(params.name == '失败')
#             return '\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n' + params.name + ' : ' + params.value;
#         if(params.name.length < 17)
#             return params.name.substring(0, 9) + '\\n' + params.name.substring(9, 17);
#         return params.name.substring(0, 9) + '\\n' + params.name.substring(9, 17) + '...';
#     }
#     """
#
# def new_label_opts():
#     return opts.LabelOpts(formatter=JsCode(fn), position="center", color='black')
#
# def myCharts(datas, chartType='pie', dataFrom='inner'):
#     if not isinstance(datas, (tuple, list)):
#         return 'datas的数据类型必须为列表或者元组'
#
#     # 为了使用调度时能实时获取数据库中的数据，添加了数据来源：dataFrom='inner'表示直接通过下面的sql获取；等于其他时表示从传递的datas获取
#     if str(dataFrom).lower() == 'inner':
#         sql_summary = '''
#                         SELECT c.s_plan_name, c.succ_count, c.fail_count, c.create_at FROM case_run_res_summary c
#                         INNER JOIN
#                         (SELECT s_plan_id, MAX(create_at) create_at FROM case_run_res_summary WHERE run_type = '1' GROUP BY s_plan_id) a
#                         ON a.s_plan_id = c.s_plan_id AND c.create_at = a.create_at WHERE c.succ_count != 0 OR c.fail_count != 0 ORDER BY create_at DESC
#                         '''
#         datas = sparrowDB.get_all(sql_summary)
#     if chartType.lower() == 'pie':
#         c = Pie(init_opts=opts.InitOpts(width="100%", height="900px"))
#         row_1_x_start = 10
#         row_1_y_start = 20
#         pieNum = min(15, len(datas))
#         countPie = 0
#         for i in range(0,3):
#             for j in range(0, 5):
#                 row_1_x = str(row_1_x_start + 20*j) + "%"
#                 row_1_y = str(row_1_y_start + 30*i) + "%"
#                 if countPie < pieNum:
#                     c.add(
#                         datas[countPie][0],
#                         [list(z) for z in zip([datas[countPie][0], '时间',"成功", "失败"], [0, str(datas[countPie][3]), datas[countPie][1], datas[countPie][2]])],
#                         center=[row_1_x, row_1_y],
#                         radius=[75, 120],
#                         label_opts=new_label_opts(),
#                     )
#                     countPie += 1
#                 else:
#                     break
#
#         c.set_colors(["#000000", "#000000", "#32CD32", "#FF0000"])
#         c.set_global_opts(
#             title_opts=opts.TitleOpts(title="小麻雀接口监控"),
#             legend_opts=opts.LegendOpts(is_show=False),
#         )
#         c.add_dataset()
#         c.render(renderHtmlPath)

# ********************************** 生成html文件 ******************************

# 链式调用实现，无法使用for循环
# c = (
#     Pie(init_opts=opts.InitOpts(width="1200px", height="700px"))
#         .add(
#         "",
#         [list(z) for z in zip(["首页添加购物车购买商品并支付成功后提供菜单","成功", "失败"], [0, 25, 75])],
#         center=["10%", "20%"],
#         radius=[60, 80],
#         label_opts=new_label_opts(),
#     )
#         .add(
#         "",
#         [list(z) for z in zip(["我的页面购物车","成功", "失败"] , [0, 325, 75])],
#         center=["25%", "20%"],
#         radius=[60, 80],
#         label_opts=new_label_opts(),
#     )
#         .set_colors(["#000000", "#32CD32", "#FF0000"])
#         .set_global_opts(
#         title_opts=opts.TitleOpts(title="小麻雀接口监控"),
#         legend_opts=opts.LegendOpts(is_show=False),
#
#     )
#         .render(renderHtmlPath)
# )
